#include <QByteArray>
#include <QCryptographicHash>
#include <QDialogButtonBox>
#include <QFile>
#include <QFileDialog>
#include <QMessageBox>
#include <QPixmap>
#include <QPushButton>
#include <QUuid>

#include "caddfielddialog.h"
#include "ui_caddfielddialog.h"
#include "centry.h"

CAddFieldDialog::CAddFieldDialog(CEntry *e, QWidget *parent) :
    QDialog(parent), m_ui(new Ui::CAddFieldDialog), m_entry(e)
{
    m_ui->setupUi(this);
    m_ui->buttonBox->button(QDialogButtonBox::Ok)->setEnabled(false);

    //m_ui->parentLbl->setText(e->getData(CEntry::Name, true).toString());
    setWindowTitle(tr("Field of %1").arg(e->getData(CEntry::Name, true).toString()));

    connect(this, SIGNAL(rejected()), this, SLOT(deleteLater()));
    connect(this, SIGNAL(accepted()), this, SLOT(process()));

    connect(m_ui->nameEdit, SIGNAL(textChanged(QString)), this, SLOT(checkFields()));
    connect(m_ui->textEdit, SIGNAL(textChanged(QString)), this, SLOT(checkFields()));
    connect(m_ui->passEdit, SIGNAL(textChanged(QString)), this, SLOT(checkFields()));
    connect(m_ui->urlEdit, SIGNAL(textChanged(QString)), this, SLOT(checkFields()));

    connect(m_ui->imageBrowseBtn, SIGNAL(clicked()), this, SLOT(openImage()));
    connect(m_ui->fileBrowseBtn, SIGNAL(clicked()), this, SLOT(openFile()));
}

CAddFieldDialog::~CAddFieldDialog()
{
    delete m_ui;
}

void CAddFieldDialog::changeEvent(QEvent *e)
{
    QDialog::changeEvent(e);
    switch (e->type()) {
    case QEvent::LanguageChange:
        m_ui->retranslateUi(this);
        break;
    default:
        break;
    }
}

void CAddFieldDialog::checkFields()
{
    if(!m_ui->nameEdit->text().length())
    {
        m_ui->buttonBox->button(QDialogButtonBox::Ok)->setEnabled(false);
        return;
    }

    bool result;
    switch(m_ui->toolBox->currentIndex())
    {
        case CEntryField::Text: result = m_ui->textEdit->text().length();
            break;

        case CEntryField::Password: result = m_ui->passEdit->text().length();
            break;

        case CEntryField::Url: result = m_ui->urlEdit->text().length();
            break;

        case CEntryField::Image: result = m_ui->previewLbl->pixmap();
            break;

        case CEntryField::File: result = m_ui->filePathEdit->text().length();
            break;
    }

    m_ui->buttonBox->button(QDialogButtonBox::Ok)->setEnabled(result);
}

void CAddFieldDialog::openImage()
{
    QString filename = QFileDialog::getOpenFileName(this, tr("Choose image"), "",
                                                    tr("Images (*.png *.jpg *.gif)"));
    if(filename.isNull())
        return;

    QPixmap pix(filename);
    if(pix.isNull())
    {
        QMessageBox::critical(this, tr("Error!"), tr("File %1 is not a correct image.").arg(filename));
        return;
    }
    m_ui->imagePathEdit->setText(filename);
    m_ui->previewLbl->setPixmap(pix);

    checkFields();
}

void CAddFieldDialog::openFile()
{
    QString filename = QFileDialog::getOpenFileName(this, tr("Choose file"), "",
                                                    tr("Any file (*.*)"));

    if(filename.isNull())
        return;

    QFile file(filename);
    if(!file.open(QIODevice::ReadOnly))
    {
        QMessageBox::critical(this, tr("Error!"), tr("Can't open specified file"));
        return;
    }

    m_ui->filePathEdit->setText(filename);
    m_ui->sizeLbl->setText(QString::number(file.size()));

    file.close();

    checkFields();
}

void CAddFieldDialog::process()
{
    emit field(this);
}

int CAddFieldDialog::type()
{
    return m_ui->toolBox->currentIndex();
}

QString CAddFieldDialog::entry_id()
{
    return m_entry->id();
}

QVariant CAddFieldDialog::name()
{
    return m_ui->nameEdit->text().toUtf8();
}

QVariant CAddFieldDialog::value()
{
    QVariant result;

    switch(m_ui->toolBox->currentIndex())
    {
        case CEntryField::Text: result = m_ui->textEdit->text().toUtf8();
            break;

        case CEntryField::Password: result = m_ui->passEdit->text().toUtf8();
            break;

        case CEntryField::Url: result = m_ui->urlEdit->text().toUtf8();
            break;

        case CEntryField::Image:
        {
            QPixmap pix(m_ui->imagePathEdit->text());

            QByteArray result;
            QBuffer buf(&result);
            pix.save(&buf, "PNG");

            return result;
        }
        default:
        {
            QString filename = m_ui->filePathEdit->text();

            QFile file(filename);
            if(!file.open(QIODevice::ReadOnly))
                result = QVariant();
            else
                result = file.readAll();
            file.close();
        }
    }

    return result;
}

int CAddFieldDialog::order()
{
    return m_ui->orderBox->text().toInt();
}

QMap<QString, QVariant> CAddFieldDialog::map()
{
    QMap<QString, QVariant> result;

    result.insert("type", type());
    result.insert("entry_id", entry_id());
    result.insert("name", name());
    result.insert("value", value());
    result.insert("order", order());

    QCryptographicHash hash(QCryptographicHash::Md5);
    QUuid salt = QUuid::createUuid();
    QString str = QDateTime::currentDateTime().toString("yyyyMMddhhmmsszzz") + salt.toString();
    hash.addData(str.toLatin1());
    QByteArray arr = hash.result();

    result.insert("id", QString(arr.toHex()).toUpper());

    return result;
}

QStringList CAddFieldDialog::blobs()
{
    QStringList result;

    result << "name" << "value";

    return result;
}

void CAddFieldDialog::setField(CEntryField *f)
{
    switch(f->type)
    {
        case CEntryField::Password: m_ui->passEdit->setText(f->value().toString());
            break;

        case CEntryField::Text: m_ui->textEdit->setText(f->value().toString());
            break;

        case CEntryField::Url: m_ui->urlEdit->setText(f->value().toString());
            break;
    }
    m_ui->nameEdit->setText(f->name());
    m_ui->toolBox->setCurrentIndex(f->type);
}
